package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("EventhazardService")
@Transactional

public class EventhazardServiceImpl extends CmiEmaService implements EventhazardService {
	public EventhazardServiceImpl() {
	}

	@Transactional
	public Eventhazard saveEventhazard(Eventhazard eventhazard) {

		if (eventhazard.getId() == null) {
			Event event = eventDAO.findEventById(eventhazard.getEvent().getId());
			Hazard hazard = hazardDAO.findHazardById(eventhazard.getHazard().getId());

			Eventhazard existingEventhazard = eventhazardDAO.findEventhazardByPhysicalPrimaryKey(event.getId(),
					hazard.getId());

			eventhazard.setEvent(event);
			eventhazard.setHazard(hazard);

			if (isEquals(eventhazard, existingEventhazard)) {
				return existingEventhazard;
			}

			eventhazard = eventhazardDAO.store(eventhazard);
			eventhazardDAO.flush();

		} else {
			Eventhazard existingEventhazard = eventhazardDAO.findEventhazardByPrimaryKey(eventhazard.getId());

			eventhazard = eventhazardDAO.store(eventhazard);
			eventhazardDAO.flush();
		}

		return eventhazard;
	}

	public void deleteEventhazard(Eventhazard eventhazard) {
		eventhazardDAO.remove(eventhazard);
		eventhazardDAO.flush();
	}

	@Transactional
	public void deleteEventhazards(Set<Integer> deleteEventhazardsId) {
		Query query = eventhazardDAO.createNamedQuery("deleteEventhazardsById", -1, -1);
		query.setParameter(1, deleteEventhazardsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Eventhazard> loadEventhazards() {
		return eventhazardDAO.findAllEventhazards();

	}

	@Transactional
	public Set<Eventhazard> loadReferenceEventhazards(Set<Eventhazard> eventhazards) {
		Iterator<Eventhazard> eventhazardsIterator = eventhazards.iterator();
		Set<Eventhazard> referencedEventhazards = new HashSet<>();
		while (eventhazardsIterator.hasNext()) {
			Eventhazard currentEventhazard = eventhazardsIterator.next();

		}
		return referencedEventhazards;
	}

	public Set<Eventhazard> loadEventhazardsByIdSet(Set<Integer> eventhazardIdSet) {

		Iterator<Integer> eventhazardIdIterator = eventhazardIdSet.iterator();
		Set<Eventhazard> eventhazardSet = new HashSet<>();
		while (eventhazardIdIterator.hasNext()) {
			Integer id = eventhazardIdIterator.next();
			Eventhazard currentEventhazard = eventhazardDAO.findEventhazardById(id);
			eventhazardSet.add(currentEventhazard);
		}
		return eventhazardSet;
	}

	@Transactional
	public List<Eventhazard> findAllEventhazards(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Eventhazard>(eventhazardDAO.findAllEventhazards(startResult, maxRows));
	}

	@Transactional
	public Eventhazard findEventhazardByPrimaryKey(Integer id) {
		return eventhazardDAO.findEventhazardByPrimaryKey(id);
	}

	@Transactional
	public Integer countEventhazards() {
		return ((Long) eventhazardDAO.createQuerySingleResult("select count(o) from Eventhazard o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countEventhazards(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Eventhazard.class);
		return ((Long) eventhazardDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countEventhazardsByName(String queryName) {
		Query query = eventhazardDAO.createNamedQuery("countEventhazardsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countEventhazardsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Eventhazard.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadEventhazardObjectReferencedSet(Eventhazard eventhazard) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (eventhazard.getEvent() != null) {

			Set<Integer> eventIds = new HashSet<Integer>();
			eventIds.add(eventhazard.getEvent().getId());
			objectReferencedSetMap.put("eventIds", eventIds);
		}
		if (eventhazard.getHazard() != null) {

			Set<Integer> hazardIds = new HashSet<Integer>();
			hazardIds.add(eventhazard.getHazard().getId());
			objectReferencedSetMap.put("hazardIds", hazardIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadEventhazardClassReferencedSet(Eventhazard eventhazard) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("events", eventDAO.findAllEvents());
		classReferencedSetMap.put("hazards", hazardDAO.findAllHazards());

		return classReferencedSetMap;
	}

	public boolean isEquals(Eventhazard eventhazard, Object obj) {
		if (obj == eventhazard)
			return true;
		if (!(obj instanceof Eventhazard))
			return false;
		Eventhazard comparedEventhazard = (Eventhazard) obj;
		if (!CheckPropertyEqual(eventhazard.getEvent().getId(), comparedEventhazard.getEvent().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(eventhazard.getHazard().getId(), comparedEventhazard.getHazard().getId())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

